#!/bin/sh

export K8S_OPENSHIFT_VERSION="${K8S_OPENSHIFT_VERSION:-3.11.0}"
export K8S_MINISHIFT_CPUS="${K8S_MINISHIFT_CPUS:-2}"
export K8S_MINISHIFT_MEMORY="${K8S_MINISHIFT_MEMORY:-4GB}"
export K8S_MINISHIFT_DISK="${K8S_MINISHIFT_DISK:-20GB}"
export K8S_MINISHIFT_VMDRIVER="${K8S_MINISHIFT_VMDRIVER:-kvm}"

get_k8s_env_version() {
  echo "minishift version $(minishift version | head -n 1 | cut -d ' ' -f 2)"
  echo
}

update_minishift_config() {
  eval "$(minishift oc-env)"

  if ! timeout -s KILL 10s oc login -u system:admin > /dev/null 2>&1
  then
    minishift status | grep '^OpenShift:  Running '
    wait_until eval 'timeout -s KILL 10s oc login -u system:admin > /dev/null 2>&1'
  fi

  local OPENSHIFT_TARGET
  for OPENSHIFT_TARGET in kube node master
  do
    # Workaround for https://github.com/minishift/minishift/issues/3290
    minishift openshift config view --target="$OPENSHIFT_TARGET" \
      | grep -A 1 'cluster-signing-cert-file:' | grep -q '/etc/origin/master/ca.crt' \
      || minishift openshift config set --target="$OPENSHIFT_TARGET" --patch '{
        "kubernetesMasterConfig": {
          "controllerArguments": {
            "cluster-signing-cert-file": ["/etc/origin/master/ca.crt"],
            "cluster-signing-key-file": ["/etc/origin/master/ca.key"],
            "feature-gates": ["PodShareProcessNamespace=true"]
          },
          "apiServerArguments": {
            "feature-gates":  ["PodShareProcessNamespace=true"]
          }
        },
        "kubeletArguments": {
          "feature-gates": ["PodShareProcessNamespace=true"]
        }
      }'

    if ! timeout -s KILL 10s oc login -u system:admin > /dev/null 2>&1
    then
      wait_until eval 'timeout -s KILL 10s oc login -u system:admin > /dev/null 2>&1'
    fi
  done

  if ! minishift ssh -- ps -ef | grep '[k]ubelet' | grep -q 'PodShareProcessNamespace=true'
  then
    minishift stop || true
    wait_until minishift stop
    minishift start
  fi

  if ! timeout -s KILL 10s oc login -u system:admin > /dev/null 2>&1
  then
    minishift status | grep '^OpenShift:  Running '
    wait_until eval 'timeout -s KILL 10s oc login -u system:admin > /dev/null 2>&1'
  fi
  for addon in admissions-webhook
  do
    minishift addons list | grep -q "^- $addon\s\+: enabled\s" \
     || ( minishift addons enable "$addon" && minishift addons apply "$addon" \
        && if ! timeout -s KILL 10s oc login -u system:admin > /dev/null 2>&1
        then
          wait_until eval 'timeout -s KILL 10s oc login -u system:admin > /dev/null 2>&1'
        fi )
  done

  oc adm policy add-scc-to-user hostmount-anyuid -n default -z default
}

update_k8s_config() {
  mkdir -p "$HOME/.kube"
  if [ "$K8S_FROM_DIND" = true ]
  then
    echo "Can not use minishift environment from docker"
    exit 1
  else
    oc config view --raw > "$HOME/.kube/config-oc"
  fi

  (
  export KUBECONFIG="${KUBECONFIG:-$HOME/.kube/config}"
  if [ -s "$KUBECONFIG" ]
  then
    KUBECONFIG="$HOME/.kube/config-oc":"$KUBECONFIG" \
      kubectl config view --raw > "$HOME/.kube/config-merged"
    mv "$HOME/.kube/config-merged" "$KUBECONFIG"
  else
    mv "$HOME/.kube/config-oc" "$KUBECONFIG"
  fi
  )
  chmod 700 "$KUBECONFIG"
}

reuse_k8s() {
  local RESULT
  local EXIT_CODE
  try_function update_minishift_config

  if ! "$RESULT" > /dev/null 2>&1
  then
    echo "Can not reuse minishift environment"
    exit 1
  fi

  echo "Reusing minishift environment"
  update_minishift_config
  update_k8s_config
}

reset_k8s() {
  if [ "$K8S_SKIP_RESET" = "true" ]
  then
    exit 1
  fi

  echo "Setting up minishift environment..."

  minishift delete -f || true

  rm -Rf "$HOME/.minishift/config" \
    "$HOME/.minishift/machines" \
    "$HOME/.minishift/certs"

  minishift start --openshift-version "v$K8S_OPENSHIFT_VERSION" \
    --cpus "$K8S_MINISHIFT_CPUS" \
    --memory "$K8S_MINISHIFT_MEMORY" \
    --disk-size "$K8S_MINISHIFT_DISK" \
    --vm-driver "$K8S_MINISHIFT_VMDRIVER"

  update_minishift_config

  update_k8s_config

  echo "...done"
}

delete_k8s() {
  echo "Deleting minishift environment..."

  minishift delete -f || true

  echo "...done"
}

load_image_k8s() {
  echo "Loading image $1 in minishift environemnt..."

  docker save "$1" | (eval "$(minishift docker-env)"; docker load)

  echo "...done"
}

excluded_namespaces() {
  echo 'kube.*'
  echo 'openshift.*'
}

excluded_customresourcedefinitions() {
  echo '.*.coreos.com'
  echo '.*.openshift.io'
}
